package cn.wsn2018.tools.service;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.dao.ProtocolConfigDao;
import cn.wsn2018.tools.dao.ProtocolTestDao;
import cn.wsn2018.tools.model.Config.ProtocolConfig;
import cn.wsn2018.tools.model.*;
import cn.wsn2018.tools.model.Exception;
import cn.wsn2018.tools.model.Report.AuthNeg;
import cn.wsn2018.tools.model.Report.EncryptNeg;
import cn.wsn2018.tools.model.VO.TestReportView;
import cn.wsn2018.tools.util.HttpUtil;
import cn.wsn2018.tools.util.JsonUtil;
import cn.wsn2018.tools.util.LogUtil;
import cn.wsn2018.tools.util.Regex;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by NZX on 2018/12/24.
 */
@Service
public class ProtocolTestService {

    @Autowired
    private ProtocolConfigDao protocolConfigDao;

    @Autowired
    private ProtocolTestDao protocolTestDao;


    /** 将对象装换为map
     *
     * @param bean
     * @return
     */
    public static <T> Map<String, String> beanToMap(T bean) {
        Map<String, String> map = new HashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key).toString());
            }
        }
        return map;
    }


    /**
     *
     * @param designId
     * @param username
     * @param protocolName
     * @param resultMap
     * @return
     */
    public String dealTestReportSave(String designId,String username,String protocolName,Map<String,String> resultMap,List<String> attackList){
        double wholeTime = 0.0;
        MyReportContext myReportContext = MyReportContext.getReportContext();
        TestReport testReport = myReportContext.getMyReport(username);

        if(testReport==null){
            testReport = new TestReport();
        }
        if(resultMap!=null&&resultMap.size()!=0){
            testReport.setDesignId(designId);
            testReport.setUsername(username);
            String protocolAllName = "";
            for(String key : CommonValue.protocolMap.keySet()){
                if(CommonValue.protocolMap.get(key).equals(protocolName)){
                    protocolAllName = key;
                }
            }
            testReport.setProtocolName(protocolAllName);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            testReport.setCreateTime(sdf.format(date));

            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);


            //认证协商
            /*zero rtt authentication ok
            key: uL8aaRqY3oRzMMX3N5eO5S2cMnMzoCWhPut6NvFd29o=
            time:3.527 ms
            clientRandom:pChREA4a3Srs91_JOtCcJExAb4m1TN6h
            severRandom:zmkKPuOz9x6GF2iopdsV8IzZgE1UIwog
            mac:5722523097
            SS:y606lPM+Ygp0K/cskJFN8cNs7of0KGDVm1PUUEbyxaY=
            start time:2019/08/07 17:44:22:498
            end time:2019/08/07 17:44:22:504
            攻击类型选择:中间人攻击
            攻击过程信息:接收传输随机数种子:pChREA4a3Srs91_JOtCcJExAb4m1TN6h，构造随机数种子:pChREA4a3Srs91_JOtCcJExAb4m1TN6h，随机数验证不通过，成功识别中间人攻击
*/
            String authResult = resultMap.get("authNegoResult");
            if(authResult!=null){
                AuthNeg authNeg = new AuthNeg();
                String[] authResultList = authResult.split(",");
                if(authResultList[0].toLowerCase().indexOf("ok")!=-1&&authResultList[1].toLowerCase().indexOf("but")==-1){
                    authNeg.setResult(CommonValue.SUCCESS);
                    String[] startArray = authResultList[7].split(":");
                    String[] endArray = authResultList[8].split(":");
                    authNeg.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                    authNeg.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);
                    String time = authResultList[2].split(":")[1].trim();
                    time = time.substring(0,time.indexOf("ms")-1);
                    authNeg.setTime(time);
                    wholeTime = wholeTime+Double.valueOf(time);
                    authNeg.setMethod(config.getAuthType());
                    authNeg.setClientSeed(authResultList[3].split(":")[1].trim());
                    authNeg.setServerSeed(authResultList[4].split(":")[1].trim());
                    authNeg.setSS(authResultList[6].split(":")[1].trim());
                    authNeg.setMac(authResultList[5].split(":")[1].trim());
                    authNeg.setKey(authResultList[1].split(":")[1].trim());
                    if(attackList.contains(CommonValue.FUNCTION_AUTHNEGO)){
                        authNeg.setAttack("中间人攻击");
                        authNeg.setAttackInfo(authResult.substring(authResult.indexOf("攻击过程信息")+7));
                    }else {
                        authNeg.setAttack("");
                        authNeg.setAttackInfo("");
                    }
                    testReport.setAuthNeg(authNeg);
                }else {
                    authNeg.setResult(CommonValue.FAILED);
                    testReport.setAuthNeg(authNeg);
                }

            }



            //加密协商
            //encryptNegotiate ok, host has received clipers ,time:1.094 ms,starttime:2019/08/07 17:53:59:733,endtime:2019/08/07 17:53:59:736
            String ENResult = resultMap.get("encryptNegoResult");
            if(ENResult!=null){
                EncryptNeg encryptNeg = new EncryptNeg();
                String[] ENResultList = ENResult.split(",");
                if(ENResultList[0].toLowerCase().indexOf("ok")!=-1&&ENResultList[1].toLowerCase().indexOf("but")==-1){
                    encryptNeg.setResult(CommonValue.SUCCESS);
                    String[] startArray = ENResultList[3].split(":");
                    String[] endArray = ENResultList[4].split(":");
                    encryptNeg.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                    encryptNeg.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);

                    String time = ENResultList[2].split(":")[1].trim();
                    time = time.substring(0,time.indexOf("ms")-1);
                    encryptNeg.setTime(time);
                    wholeTime = wholeTime+Double.valueOf(time);
                    encryptNeg.setInfo(ENResultList[1]);
                    testReport.setEncryptNeg(encryptNeg);
                }else {
                    encryptNeg.setResult(CommonValue.FAILED);
                    testReport.setEncryptNeg(encryptNeg);
                }
            }



            //加密
            /*encrypt ok
            using method: AES
            time:0.06 ms
            data before: RQAAQ75yQAA/BvjVwKgBDsCo
            data after: RQAAQ75yQAA/BvjVwKgBDsCoAg7u/04g
            using key:a2lqbmF3aWt3aWd1
            攻击类型选择:数据包窃听
            攻击过程信息:接收密文: RQAAQ75yQAA/BvjVwKgBDsCoAg7u/04g，随机生成密钥:r41VtZ3txWOoME1w，解密后数据:r41VtZ3txWOoME1wu6w5M6tOeFS3lIUO，攻击者无法识别密文，安全协议能够抵御数据包窃听
*/          String EResult = resultMap.get("encryptResult");
            if(EResult!=null){
                cn.wsn2018.tools.model.Report.Encrypt encrypt = new cn.wsn2018.tools.model.Report.Encrypt();
                String[] EResultList = EResult.split(",");
                if(EResultList[0].toLowerCase().indexOf("ok")!=-1&&EResultList[1].toLowerCase().indexOf("but")==-1){
                    encrypt.setResult(CommonValue.SUCCESS);

                    String[] startArray = EResultList[6].split(":");
                    String[] endArray = EResultList[7].split(":");
                    encrypt.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                    encrypt.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);

                    String time = EResultList[2].split(":")[1].trim();
                    time = time.substring(0,time.indexOf("ms")-1);
                    encrypt.setTime(time);
                    wholeTime = wholeTime+Double.valueOf(time);
                    encrypt.setMethod(EResultList[1].split(":")[1].trim());
                    encrypt.setKey(EResultList[5].split(":")[1].trim());
                    encrypt.setBefore(EResultList[3].split(":")[1].trim());
                    encrypt.setAfter(EResultList[4].split(":")[1].trim());
                    if(attackList.contains(CommonValue.FUNCTION_ENCRYPT)){
                        encrypt.setAttack("数据包窃听");
                        encrypt.setAttackInfo(EResult.substring(EResult.indexOf("攻击过程信息")+7));
                    }else {
                        encrypt.setAttack("");
                        encrypt.setAttackInfo("");
                    }

                    testReport.setEncrypt(encrypt);
                }else {
                    encrypt.setResult(CommonValue.FAILED);
                    testReport.setEncrypt(encrypt);
                }
            }



            //异常
            /*scaning ok
            using scaning tools
            time:3 ms
            head length:40
            head:RQAAQ74WQAA/BvkxwKgBDsCoAg7u/04gVlHsIbJXwhpQGAP/VDwAAA==
            total_length:70
            actual length:73
            result: error packet found
            攻击类型选择:数据包篡改
            攻击过程信息:篡改数据包长度为:73，检测到长度不匹配，安全协议成功识别数据包篡改*/
            String EXResult = resultMap.get("exceptionResult");
            if(EXResult!=null){
                cn.wsn2018.tools.model.Report.Exception exception = new cn.wsn2018.tools.model.Report.Exception();
                String[] EXResultList = EXResult.split(",");
                if(EXResultList[0].toLowerCase().indexOf("ok")!=-1&&EXResultList[1].toLowerCase().indexOf("but")==-1){
                    exception.setResult(CommonValue.SUCCESS);
                    String[] startArray = EXResultList[8].split(":");
                    String[] endArray = EXResultList[9].split(":");
                    exception.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                    exception.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);

                    String time = EXResultList[2].split(":")[1].trim();
                    time = time.substring(0,time.indexOf("ms")-1);
                    exception.setTime(time);
                    wholeTime = wholeTime+Double.valueOf(time);
                    exception.setInfo(EXResultList[7].split(":")[1]);
                    exception.setHeadLength(EXResultList[3].split(":")[1].trim());
                    exception.setTotalLength(EXResultList[5].split(":")[1].trim());
                    exception.setActualLength(EXResultList[6].split(":")[1].trim());
                    exception.setHeadInfo(EXResultList[4].split(":")[1].trim());
                    if (attackList.contains(CommonValue.FUNCTION_EXCEPTION)){
                        exception.setAttack("数据包篡改");
                        exception.setAttackInfo(EXResult.substring(EXResult.indexOf("攻击过程信息")+7));
                    }else {
                        exception.setAttack("");
                        exception.setAttackInfo("");
                    }

                    testReport.setException(exception);
                }else {
                    exception.setResult(CommonValue.FAILED);
                    testReport.setException(exception);
                }
            }



            //完整性校验
            /*vertify ok
            using method: MD5
            time:0.026 ms
            hash value:1002
            data_area:RQAAQ744QAA/BvkPwKgBDsCoAg7u/04gVlHt3bJXyqNQGA
            verify value:6210
            攻击类型选择:数据包篡改
            攻击过程信息:篡改前校验值:1002，篡改后校验值:6210，校验不通过，安全协议成功识别数据包篡改*/
            String IResult = resultMap.get("integrityResult");
            if(IResult!=null){
                cn.wsn2018.tools.model.Report.Integrity integrity = new cn.wsn2018.tools.model.Report.Integrity();
                String[] IResultList = IResult.split(",");
                if(IResultList[0].toLowerCase().indexOf("ok")!=-1&&IResultList[1].toLowerCase().indexOf("but")==-1){
                    integrity.setResult(CommonValue.SUCCESS);
                    String[] startArray = IResultList[6].split(":");
                    String[] endArray = IResultList[7].split(":");
                    integrity.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                    integrity.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);

                    String time = IResultList[2].split(":")[1].trim();
                    time = time.substring(0,time.indexOf("ms")-1);
                    integrity.setTime(time);
                    wholeTime = wholeTime+Double.valueOf(time);
                    integrity.setMethod(IResultList[1].split(":")[1].trim());
                    integrity.setHashValue(IResultList[3].split(":")[1].trim());
                    integrity.setVerifyValue(IResultList[5].split(":")[1].trim());
                    integrity.setContent(IResultList[4].split(":")[1].trim());
                    if(attackList.contains(CommonValue.FUNCTION_INTEGRITY)){
                        integrity.setAttack("数据包篡改");
                        integrity.setAttackInfo(IResult.substring(IResult.indexOf("攻击过程信息")+7));
                    }else {
                        integrity.setAttack("");
                        integrity.setAttackInfo("");
                    }

                    testReport.setIntegrity(integrity);
                }else {
                    integrity.setResult(CommonValue.FAILED);
                    testReport.setIntegrity(integrity);
                }
            }



            //重传
            /*ARQ ok
            using arq methods
            time:3.064 ms
            result:2 message has been retransferred
            arq times:2
            success arq times:2
            arq_order:12345
            rto:0.010ms
            攻击类型选择: 重放攻击
            攻击过程信息:重放标号为3的数据包，重传队列序号重复，安全协议成功识别重放攻击*/
            String RResult = resultMap.get("resendResult");
            if(RResult!=null){
                cn.wsn2018.tools.model.Report.Resend resend = new cn.wsn2018.tools.model.Report.Resend();
                String[] RResultList = RResult.split(",");
                if(RResultList[0].toLowerCase().indexOf("ok")!=-1&&RResultList[1].toLowerCase().indexOf("but")==-1){
                    resend.setResult(CommonValue.SUCCESS);
                    String[] startArray = RResultList[8].split(":");
                    String[] endArray = RResultList[9].split(":");
                    resend.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                    resend.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);

                    String time = RResultList[2].split(":")[1].trim();
                    time = time.substring(0,time.indexOf("ms")-1);
                    resend.setTime(time);
                    wholeTime = wholeTime+Double.valueOf(time);
                    resend.setCount(RResultList[4].split(":")[1].trim());
                    resend.setSuccessCount(RResultList[5].split(":")[1].trim());
                    resend.setSequence(RResultList[6].split(":")[1].trim());
                    resend.setQueue(config.getResend().getQueue());
                    resend.setRTO(RResultList[7].split(":")[1].trim());
                    if (attackList.contains(CommonValue.FUNCTION_RESEND)){
                        resend.setAttack("重放攻击");
                        resend.setAttackInfo(RResult.substring(RResult.indexOf("攻击过程信息")+7));
                    }else {
                        resend.setAttack("");
                        resend.setAttackInfo("");
                    }

                    testReport.setResend(resend);
                }else {
                    resend.setResult(CommonValue.FAILED);
                    testReport.setResend(resend);
                }
            }

            testReport.setWholeTime(String.format("%.3f", wholeTime));
            String testReportId = protocolTestDao.saveTestReport(testReport);
            myReportContext.delMyReport(username);
            if(testReportId!=null){
                LogUtil.produceLogs(username,CommonValue.CREATE_TYPE,CommonValue.CREATE_TESTREPORT_LOGINFO+",测试报告id:T-"+(testReportId.substring(6,8)+testReportId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return testReportId;

            }else {
                LogUtil.produceLogs(username,CommonValue.CREATE_TYPE,CommonValue.CREATE_TESTREPORT_LOGINFO,CommonValue.FAILED);
                return null;
            }
        }else {
            LogUtil.produceLogs(username,CommonValue.CREATE_TYPE,CommonValue.CREATE_TESTREPORT_LOGINFO,CommonValue.FAILED);
            return null;
        }
    }

    /**
     * 测试报告详情查询
     * @param id
     * @return
     */
    public String dealTestReportQuery(String id){
        if(id!=null&&!id.isEmpty()){
            TestReport report = protocolTestDao.getTestReport(id);
            JSONObject jsonObject = JSONObject.fromObject(report);
            return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,jsonObject,null);
        }else {
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 查询某人所有报告
     * @param username
     * @param pageNum
     * @param pageSize
     * @return
     */
    public String dealTestReportsQuery(String username,String pageNum,String pageSize){
        if(username!=null&&!username.isEmpty()){
            List<TestReport> reports = protocolTestDao.getTestReports(username,pageNum,pageSize);
            List<TestReportView> reportViews = new ArrayList<>();
            for(TestReport testReport : reports){
                TestReportView reportView = new TestReportView();
                reportView.setId(testReport.getId());
                reportView.setDesignId(testReport.getDesignId());
                reportView.setProtocolName(testReport.getProtocolName());
                reportView.setCreateTime(testReport.getCreateTime());
                List<String> functions = new ArrayList<>();
                if(testReport.getAuthNeg()!=null){
                    functions.add(CommonValue.FUNCTION_AUTHNEGO);
                }
                if(testReport.getEncryptNeg()!=null){
                    functions.add(CommonValue.FUNCTION_ENCRYPTNEGO);
                }
                if(testReport.getEncrypt()!=null){
                    functions.add(CommonValue.FUNCTION_ENCRYPT);
                }
                if (testReport.getException()!=null){
                    functions.add(CommonValue.FUNCTION_EXCEPTION);
                }
                if(testReport.getResend()!=null){
                    functions.add(CommonValue.FUNCTION_RESEND);
                }
                if(testReport.getIntegrity()!=null){
                    functions.add(CommonValue.FUNCTION_INTEGRITY);
                }
                if(testReport.getVirus()!=null){
                    functions.add(CommonValue.FUNCTION_VIRUS);
                }
                reportView.setFunctions(functions);
                reportViews.add(reportView);
            }
            JSONArray jsonArray = JSONArray.fromObject(reportViews);
            return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,null,jsonArray);
        }else {
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 删除测试报告
     * @param id
     * @param myUsername
     * @return
     */
    public String dealTestReportDelete(String id,String myUsername){
        if(id!=null&&!id.isEmpty()){
            boolean result = protocolTestDao.deleteTestReport(id);
            if(result){
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_TESTREPORT_LOGINFO+",测试报告id:T-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_SUCCESS, null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_TESTREPORT_LOGINFO+"测试报告id:T-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_FAILED, null,null);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_TESTREPORT_LOGINFO+"测试报告id:T-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 批量删除测试报告
     * @param idList
     * @param myUsername
     * @return
     */
    public String dealTestReportsDelete(List<String> idList,String myUsername){
        int num = idList.size();
        if(idList!=null&&num!=0){
            int count = protocolTestDao.deleteTestReports(idList);
            if(count==num){
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_TESTREPORT_LOGINFO+num+"条",CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_SUCCESS+",计划删除"+num+
                        "条,实际删除"+count+"条",null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_TESTREPORT_LOGINFO+num+"条",CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_DELETE_FAILED+",计划删除"+num+
                        "条,实际删除"+count+"条");
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_TESTREPORT_LOGINFO+num+"条",CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 预处理信息发送
     * @param designId
     * @return
     */
    public String dealTestPreInfo(String designId){
        String EPT = "close";
        String IC = "close";
        String AD = "close";
        String EAlgor = "";
        String EMode = "";
        String IAlgor = "";
        String AAlgor = "";
        //resend
        String Auto="";
        ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);

        if(config!=null){
            Encrypt encrypt = config.getEncrypt();
            if(encrypt!=null&&encrypt.getAlgorithm()!=null){
                EPT = "open";
                EAlgor = encrypt.getAlgorithm();
                EMode = encrypt.getMode();
            }
            Integrity integrity = config.getIntegrity();
            if(integrity!=null&&integrity.getAlgorithm()!=null){
                IC = "open";
                IAlgor = integrity.getAlgorithm();
            }
            Exception exception = config.getException();
            if(exception!=null&&exception.getMethod()!=null){
                AD = "open";
                AAlgor = exception.getMethod()=="0"?"header":"length";
            }

            Resend resend = config.getResend();
            if(resend!=null&&resend.getTime()!=null&&resend.getQueue()!=null&&resend.getCount()!=null){
                Auto="state";
            }
            preMessage(config.getProtocolName(),EPT,IC,AD,EAlgor,EMode,IAlgor,AAlgor,Auto);

           //preMessage(config.getProtocolName(),EPT,IC,AD,EAlgor,EMode,IAlgor,AAlgor);
            return JsonUtil.successJson(CommonValue.PRE_MESSAGE_SEND,null,null);
        }else {
            return JsonUtil.failedJson(CommonValue.JSON_QUERY_NULL);
        }
    }

    /**
     * 认证协商测试
     * @param designId
     * @param testNum
     * @param attack
     * @param myUsername
     * @return
     */
    public String dealAuthNegoTest(String designId,String testNum,String attack,String myUsername) throws InterruptedException {
        if(designId!=null&&!"".equals(designId)&&testNum!=null&&!"".equals(testNum)&&attack!=null&&!"".equals(attack)&&myUsername!=null&&!"".equals(myUsername)) {
            designId = Regex.checkReg(designId);
            testNum = Regex.checkReg(testNum);
            attack = Regex.checkReg(attack);
            myUsername = Regex.checkReg(myUsername);
            Map resultMap = new HashMap<>();
            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if (config!=null) {
                String authType = config.getAuthType();
                String protocol = CommonValue.protocolMap.get(config.getProtocolName());
                if(protocol==null){
                    protocol = "";
                }
                if (authType != null && !authType.isEmpty()) {
                    Map<String,AuthNeg> authNegMap = new HashMap<>();
                    for (int i = 0; i < Integer.parseInt(testNum); i++) {

                        String authNegoResult = authNegotiation(authType, protocol);
                        AuthNeg authNeg = new AuthNeg();
                        if (authNegoResult!=null&&!authNegoResult.equals("inner error")) {

                            String[] authResultList = authNegoResult.split(",");
                            if(authResultList[0].toLowerCase().indexOf("ok")!=-1&&authResultList[1].toLowerCase().indexOf("but")==-1){
                                authNeg.setResult(CommonValue.SUCCESS);
                                String[] startArray = authResultList[7].split(":");
                                String[] endArray = authResultList[8].split(":");
                                authNeg.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                                authNeg.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);
                                String time = authResultList[2].split(":")[1].trim();
                                time = time.substring(0,time.indexOf("ms")-1);
                                authNeg.setTime(time);
                                authNeg.setMethod(config.getAuthType());
                                authNeg.setClientSeed(authResultList[3].split(":")[1].trim());
                                authNeg.setServerSeed(authResultList[4].split(":")[1].trim());
                                authNeg.setSS(authResultList[6].split(":")[1].trim());
                                authNeg.setMac(authResultList[5].split(":")[1].trim());
                                authNeg.setKey(authResultList[1].split(":")[1].trim());
                                if("1".equals(attack)){
                                    authNeg.setAttack("中间人攻击");
                                    authNeg.setAttackInfo(authNegoResult.substring(authNegoResult.indexOf("攻击过程信息")+7));
                                }else {
                                    authNeg.setAttack("");
                                    authNeg.setAttackInfo("");
                                }
                            }else {
                                authNeg.setResult(CommonValue.FAILED);
                            }
                            authNegMap.put(Integer.toString(i),authNeg);
                            resultMap.put(Integer.toString(i),authNegoResult);
                        }else {
                            authNeg.setResult(CommonValue.FAILED);
                            authNegMap.put(Integer.toString(i),authNeg);
                            resultMap.put(Integer.toString(i),authNegoResult);
                        }

                        Thread.sleep(150);

                    }
                    MyReportContext myReportContext = MyReportContext.getReportContext();
                    TestReport testReport = myReportContext.getMyReport(myUsername);

                    if(testReport!=null){
                        testReport.setAuthNegMap(authNegMap);
                        myReportContext.addMyReport(myUsername,testReport);
                    }else {
                        TestReport nTestReport = new TestReport();
                        nTestReport.setAuthNegMap(authNegMap);
                        myReportContext.addMyReport(myUsername,nTestReport);
                    }


                }


                JSONObject jsonObject = JSONObject.fromObject(resultMap);
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计ID:"+designId,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    public String dealEncryptNegoTest(String designId,String testNum,String myUsername) throws InterruptedException {

        if(designId!=null&&!"".equals(designId)&&testNum!=null&&!"".equals(testNum)&&myUsername!=null&&!"".equals(myUsername)) {
            designId = Regex.checkReg(designId);
            testNum = Regex.checkReg(testNum);
            myUsername = Regex.checkReg(myUsername);
            Map resultMap = new HashMap<>();
            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if (config!=null) {
                Encrypt encrypt = config.getEncrypt();
                String protocol = CommonValue.protocolMap.get(config.getProtocolName());
                if(protocol==null){
                    protocol = "";
                }
                if(encrypt!=null&&encrypt.getAlgorithm()!=null){
                    Map<String,EncryptNeg> encryptNegMap = new HashMap<>();
                    for(int i=0;i<Integer.parseInt(testNum);i++){

                        String encryNegoResult = encryptNegotiation(encrypt.getAlgorithm(),encrypt.getMode(),encrypt.getRange(),protocol);
                        EncryptNeg encryptNeg = new EncryptNeg();
                        if(encryNegoResult!=null&&!encryNegoResult.equals("inner error")){


                            String[] ENResultList = encryNegoResult.split(",");
                            if(ENResultList[0].toLowerCase().indexOf("ok")!=-1&&ENResultList[1].toLowerCase().indexOf("but")==-1){
                                encryptNeg.setResult(CommonValue.SUCCESS);
                                String[] startArray = ENResultList[3].split(":");
                                String[] endArray = ENResultList[4].split(":");
                                encryptNeg.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                                encryptNeg.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);
                                String time = ENResultList[2].split(":")[1].trim();
                                time = time.substring(0,time.indexOf("ms")-1);
                                encryptNeg.setTime(time);
                                encryptNeg.setInfo(ENResultList[1]);
                            }else {
                                encryptNeg.setResult(CommonValue.FAILED);
                            }
                            resultMap.put(Integer.toString(i),encryNegoResult);
                            encryptNegMap.put(Integer.toString(i),encryptNeg);
                        }else {
                            encryptNeg.setResult(CommonValue.FAILED);
                            resultMap.put(Integer.toString(i),encryNegoResult);
                            encryptNegMap.put(Integer.toString(i),encryptNeg);
                        }

                        Thread.sleep(150);

                    }
                    MyReportContext myReportContext = MyReportContext.getReportContext();
                    TestReport testReport = myReportContext.getMyReport(myUsername);

                    if(testReport!=null){
                        testReport.setEncryptNegMap(encryptNegMap);
                        myReportContext.addMyReport(myUsername,testReport);
                    }else {
                        TestReport nTestReport = new TestReport();
                        nTestReport.setEncryptNegMap(encryptNegMap);
                        myReportContext.addMyReport(myUsername,nTestReport);
                    }
                }

                JSONObject jsonObject = JSONObject.fromObject(resultMap);
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);

            }else {
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    public String dealEncryptTest(String designId,String testNum,String attack,String myUsername) throws InterruptedException{
        if(designId!=null&&!"".equals(designId)&&testNum!=null&&!"".equals(testNum)&&attack!=null&&!"".equals(attack)&&myUsername!=null&&!"".equals(myUsername)) {
            designId = Regex.checkReg(designId);
            testNum = Regex.checkReg(testNum);
            attack = Regex.checkReg(attack);
            myUsername = Regex.checkReg(myUsername);
            Map resultMap = new HashMap<>();
            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if (config!=null) {
                Encrypt encryp = config.getEncrypt();
                String protocol = CommonValue.protocolMap.get(config.getProtocolName());
                if(protocol==null){
                    protocol = "";
                }
                if(encryp!=null&&encryp.getAlgorithm()!=null){
                    Map<String, cn.wsn2018.tools.model.Report.Encrypt> encryptMap = new HashMap<>();
                    for(int i=0;i<Integer.parseInt(testNum);i++){

                        String encryptResult = testEncrypt(encryp.getAlgorithm(),protocol);
                        cn.wsn2018.tools.model.Report.Encrypt encrypt = new cn.wsn2018.tools.model.Report.Encrypt();
                        if(encryptResult!=null&&!encryptResult.equals("inner error")){

                            String[] EResultList = encryptResult.split(",");
                            if(EResultList[0].toLowerCase().indexOf("ok")!=-1&&EResultList[1].toLowerCase().indexOf("but")==-1){
                                encrypt.setResult(CommonValue.SUCCESS);
                                String[] startArray = EResultList[6].split(":");
                                String[] endArray = EResultList[7].split(":");
                                encrypt.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                                encrypt.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);
                                String time = EResultList[2].split(":")[1].trim();
                                time = time.substring(0,time.indexOf("ms")-1);
                                encrypt.setTime(time);
                                encrypt.setMethod(EResultList[1].split(":")[1].trim());
                                encrypt.setKey(EResultList[5].split(":")[1].trim());
                                encrypt.setBefore(EResultList[3].split(":")[1].trim());
                                encrypt.setAfter(EResultList[4].split(":")[1].trim());
                                if("1".equals(attack)){
                                    encrypt.setAttack("数据包窃听");
                                    encrypt.setAttackInfo(encryptResult.substring(encryptResult.indexOf("攻击过程信息")+7));
                                }else {
                                    encrypt.setAttack("");
                                    encrypt.setAttackInfo("");
                                }

                            }else {
                                encrypt.setResult(CommonValue.FAILED);
                            }
                            resultMap.put(Integer.toString(i),encryptResult);
                            encryptMap.put(Integer.toString(i),encrypt);
                        }else{
                            encrypt.setResult(CommonValue.FAILED);
                            resultMap.put(Integer.toString(i),encryptResult);
                            encryptMap.put(Integer.toString(i),encrypt);
                        }

                        Thread.sleep(150);
                    }
                    MyReportContext myReportContext = MyReportContext.getReportContext();
                    TestReport testReport = myReportContext.getMyReport(myUsername);

                    if(testReport!=null){
                        testReport.setEncryptMap(encryptMap);
                        myReportContext.addMyReport(myUsername,testReport);
                    }else {
                        TestReport nTestReport = new TestReport();
                        nTestReport.setEncryptMap(encryptMap);
                        myReportContext.addMyReport(myUsername,nTestReport);
                    }
                    //String encryptResult = "encrypt ok ,using method: AES ,time:78 ms\u0000\u0000\u0000\u0000";
                }

                JSONObject jsonObject = JSONObject.fromObject(resultMap);
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    public String dealExceptionTest(String designId,String testNum,String attack,String myUsername) throws InterruptedException{
        if(designId!=null&&!"".equals(designId)&&testNum!=null&&!"".equals(testNum)&&attack!=null&&!"".equals(attack)&&myUsername!=null&&!"".equals(myUsername)) {
            designId = Regex.checkReg(designId);
            testNum = Regex.checkReg(testNum);
            attack = Regex.checkReg(attack);
            myUsername = Regex.checkReg(myUsername);
            Map resultMap = new HashMap<>();
            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if (config!=null) {
                String protocol = CommonValue.protocolMap.get(config.getProtocolName());
                if(protocol==null){
                    protocol = "";
                }
                Exception excep = config.getException();
                if(excep!=null&&excep.getMethod()!=null){
                    Map<String, cn.wsn2018.tools.model.Report.Exception> exceptionMap = new HashMap<>();
                    for(int i=0;i<Integer.parseInt(testNum);i++){

                        String excepResult = testException(protocol);
                        cn.wsn2018.tools.model.Report.Exception exception = new cn.wsn2018.tools.model.Report.Exception();
                        if(excepResult!=null&&!excepResult.equals("inner error")){

                            String[] EXResultList = excepResult.split(",");
                            if(EXResultList[0].toLowerCase().indexOf("ok")!=-1&&EXResultList[1].toLowerCase().indexOf("but")==-1){
                                exception.setResult(CommonValue.SUCCESS);
                                String[] startArray = EXResultList[8].split(":");
                                String[] endArray = EXResultList[9].split(":");
                                exception.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                                exception.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);
                                String time = EXResultList[2].split(":")[1].trim();
                                time = time.substring(0,time.indexOf("ms")-1);
                                exception.setTime(time);
                                exception.setInfo(EXResultList[7].split(":")[1]);
                                exception.setHeadLength(EXResultList[3].split(":")[1].trim());
                                exception.setTotalLength(EXResultList[5].split(":")[1].trim());
                                exception.setActualLength(EXResultList[6].split(":")[1].trim());
                                exception.setHeadInfo(EXResultList[4].split(":")[1].trim());
                                if ("1".equals(attack)){
                                    exception.setAttack("数据包篡改");
                                    exception.setAttackInfo(excepResult.substring(excepResult.indexOf("攻击过程信息")+7));
                                }else {
                                    exception.setAttack("");
                                    exception.setAttackInfo("");
                                }

                            }else {
                                exception.setResult(CommonValue.FAILED);
                            }
                            resultMap.put(Integer.toString(i),excepResult);
                            exceptionMap.put(Integer.toString(i),exception);
                        }else {
                            exception.setResult(CommonValue.FAILED);
                            resultMap.put(Integer.toString(i),excepResult);
                            exceptionMap.put(Integer.toString(i),exception);
                        }

                        Thread.sleep(150);
                    }
                    MyReportContext myReportContext = MyReportContext.getReportContext();
                    TestReport testReport = myReportContext.getMyReport(myUsername);

                    if(testReport!=null){
                        testReport.setExceptionMap(exceptionMap);
                        myReportContext.addMyReport(myUsername,testReport);
                    }else {
                        TestReport nTestReport = new TestReport();
                        nTestReport.setExceptionMap(exceptionMap);
                        myReportContext.addMyReport(myUsername,nTestReport);
                    }

                    //String excepResult = "scaning ok , result: no error msg ,time:2221 ms\u0000\u0000\u0000\u0000";

                }


                JSONObject jsonObject = JSONObject.fromObject(resultMap);
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);

            }else {
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    public String dealIntegrityTest(String designId,String testNum,String attack,String myUsername) throws InterruptedException{
        if(designId!=null&&!"".equals(designId)&&testNum!=null&&!"".equals(testNum)&&attack!=null&&!"".equals(attack)&&myUsername!=null&&!"".equals(myUsername)) {
            designId = Regex.checkReg(designId);
            testNum = Regex.checkReg(testNum);
            attack = Regex.checkReg(attack);
            myUsername = Regex.checkReg(myUsername);
            Map resultMap = new HashMap<>();
            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if (config!=null) {
                String protocol = CommonValue.protocolMap.get(config.getProtocolName());
                if(protocol==null){
                    protocol = "";
                }
                Integrity integ = config.getIntegrity();
                if(integ!=null&&integ.getAlgorithm()!=null){
                    Map<String, cn.wsn2018.tools.model.Report.Integrity> integrityMap = new HashMap<>();
                    for(int i=0;i<Integer.parseInt(testNum);i++){

                        String integResult = testIntegrity(integ.getAlgorithm(),protocol);
                        cn.wsn2018.tools.model.Report.Integrity integrity = new cn.wsn2018.tools.model.Report.Integrity();
                        if(integResult!=null&&!integResult.equals("inner error")){

                            String[] IResultList = integResult.split(",");
                            if(IResultList[0].toLowerCase().indexOf("ok")!=-1&&IResultList[1].toLowerCase().indexOf("but")==-1){
                                integrity.setResult(CommonValue.SUCCESS);
                                String[] startArray = IResultList[6].split(":");
                                String[] endArray = IResultList[7].split(":");
                                integrity.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                                integrity.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);
                                String time = IResultList[2].split(":")[1].trim();
                                time = time.substring(0,time.indexOf("ms")-1);
                                integrity.setTime(time);
                                integrity.setMethod(IResultList[1].split(":")[1].trim());
                                integrity.setHashValue(IResultList[3].split(":")[1].trim());
                                integrity.setVerifyValue(IResultList[5].split(":")[1].trim());
                                integrity.setContent(IResultList[4].split(":")[1].trim());
                                if("1".equals(attack)){
                                    integrity.setAttack("数据包篡改");
                                    integrity.setAttackInfo(integResult.substring(integResult.indexOf("攻击过程信息")+7));
                                }else {
                                    integrity.setAttack("");
                                    integrity.setAttackInfo("");
                                }

                            }else {
                                integrity.setResult(CommonValue.FAILED);

                            }
                            resultMap.put(Integer.toString(i),integResult);
                            integrityMap.put(Integer.toString(i),integrity);
                        }else {
                            integrity.setResult(CommonValue.FAILED);
                            resultMap.put(Integer.toString(i),integResult);
                            integrityMap.put(Integer.toString(i),integrity);
                        }

                        Thread.sleep(150);
                    }
                    MyReportContext myReportContext = MyReportContext.getReportContext();
                    TestReport testReport = myReportContext.getMyReport(myUsername);

                    if(testReport!=null){
                        testReport.setIntegrityMap(integrityMap);
                        myReportContext.addMyReport(myUsername,testReport);
                    }else {
                        TestReport nTestReport = new TestReport();
                        nTestReport.setIntegrityMap(integrityMap);
                        myReportContext.addMyReport(myUsername,nTestReport);
                    }
                    //String integResult = "vertify ok ,using method: MD5 ,time:19 ms";
                }


                JSONObject jsonObject = JSONObject.fromObject(resultMap);
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);

            }else {
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    public String dealResendTest(String designId,String testNum,String attack,String myUsername) throws InterruptedException{
        if(designId!=null&&!"".equals(designId)&&testNum!=null&&!"".equals(testNum)&&attack!=null&&!"".equals(attack)&&myUsername!=null&&!"".equals(myUsername)) {
            designId = Regex.checkReg(designId);
            testNum = Regex.checkReg(testNum);
            attack = Regex.checkReg(attack);
            myUsername = Regex.checkReg(myUsername);
            Map resultMap = new HashMap<>();
            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if (config!=null) {
                String protocol = CommonValue.protocolMap.get(config.getProtocolName());
                if(protocol==null){
                    protocol = "";
                }
                Resend resen = config.getResend();
                if(resen!=null&&resen.getQueue()!=null){
                    Map<String, cn.wsn2018.tools.model.Report.Resend> resendMap = new HashMap<>();
                    for(int i=0;i<Integer.parseInt(testNum);i++){

                        String resendResult = testResend(resen.getQueue(),resen.getTime(),resen.getCount(),protocol);
                        cn.wsn2018.tools.model.Report.Resend resend = new cn.wsn2018.tools.model.Report.Resend();
                        if(resendResult!=null&&!resendResult.equals("inner error")) {

                            String[] RResultList = resendResult.split(",");
                            if (RResultList[0].toLowerCase().indexOf("ok") != -1 && RResultList[1].toLowerCase().indexOf("but") == -1) {
                                resend.setResult(CommonValue.SUCCESS);
                                String[] startArray = RResultList[8].split(":");
                                String[] endArray = RResultList[9].split(":");
                                resend.setStartTime(startArray[1]+":"+startArray[2]+":"+startArray[3]+":"+startArray[4]);
                                resend.setEndTime(endArray[1]+":"+endArray[2]+":"+endArray[3]+":"+endArray[4]);
                                String time = RResultList[2].split(":")[1].trim();
                                time = time.substring(0,time.indexOf("ms")-1);
                                resend.setTime(time);
                                resend.setCount(RResultList[4].split(":")[1].trim());
                                resend.setSuccessCount(RResultList[5].split(":")[1].trim());
                                resend.setSequence(RResultList[6].split(":")[1].trim());
                                resend.setQueue(config.getResend().getQueue());
                                resend.setRTO(RResultList[7].split(":")[1].trim());
                                if ("1".equals(attack)) {
                                    resend.setAttack("重放攻击");
                                    resend.setAttackInfo(resendResult.substring(resendResult.indexOf("攻击过程信息") + 7));
                                } else {
                                    resend.setAttack("");
                                    resend.setAttackInfo("");
                                }

                            } else {
                                resend.setResult(CommonValue.FAILED);
                            }
                            resultMap.put(Integer.toString(i),resendResult);
                            resendMap.put(Integer.toString(i),resend);
                        }else {
                            resend.setResult(CommonValue.FAILED);
                            resultMap.put(Integer.toString(i),resendResult);
                            resendMap.put(Integer.toString(i),resend);
                        }

                        Thread.sleep(150);
                    }
                    MyReportContext myReportContext = MyReportContext.getReportContext();
                    TestReport testReport = myReportContext.getMyReport(myUsername);

                    if(testReport!=null){
                        testReport.setResendMap(resendMap);
                        myReportContext.addMyReport(myUsername,testReport);
                    }else {
                        TestReport nTestReport = new TestReport();
                        nTestReport.setResendMap(resendMap);
                        myReportContext.addMyReport(myUsername,nTestReport);
                    }
                    //String resendResult = "ARQ ok  limited times:5 ,result: 1 message has been retransferred ,time:1722 ms";
                }



                JSONObject jsonObject = JSONObject.fromObject(resultMap);
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 完整协议测试
     * @param designId
     * @param myUsername
     * @return
     */
    public String dealProtocolTest(String designId,String attacks,String myUsername) throws InterruptedException {
        if(designId!=null&&!"".equals(designId)&&attacks!=null&&!"".equals(attacks)&&myUsername!=null&&!"".equals(myUsername)) {
            designId = Regex.checkReg(designId);
            attacks = Regex.checkReg(attacks);
            myUsername = Regex.checkReg(myUsername);
            Map resultMap = new HashMap<>();

            List<String> attackList = new ArrayList<>();

            boolean status = true;

            for(String attack : attacks.split(",")){
                attackList.add(attack);
            }
            ProtocolConfig config = protocolConfigDao.getProtocolConfigByDesignId(designId);
            if (config!=null){
                String authType = config.getAuthType();
                String protocol = CommonValue.protocolMap.get(config.getProtocolName());
                if(protocol==null){
                    protocol = "";
                }
                if(authType!=null&&!authType.isEmpty()){
                    String authResult = authNegotiation(authType,protocol);
                    if(authResult.equals("inner error")) {
                        status = false;
                    }
                    Thread.sleep(150);
                    resultMap.put("authNegoResult",authResult);

                }
                Encrypt encrypt = config.getEncrypt();
                if(encrypt!=null&&encrypt.getAlgorithm()!=null){
                    String encryNegoResult = encryptNegotiation(encrypt.getAlgorithm(),encrypt.getMode(),encrypt.getRange(),protocol);
                    if(encryNegoResult.equals("inner error")) {
                        status = false;
                    }
                    Thread.sleep(150);
                    resultMap.put("encryptNegoResult",encryNegoResult);
                }

                Exception exception = config.getException();
                if(exception!=null&&exception.getMethod()!=null){
                    String excepResult = testException(protocol);
                    if(excepResult.equals("inner error")){
                        status = false;
                    }
                    Thread.sleep(150);
                    //String excepResult = "scaning ok , result: no error msg ,time:2221 ms\u0000\u0000\u0000\u0000";

                    resultMap.put("exceptionResult",excepResult);
                }
                Integrity integrity = config.getIntegrity();
                if(integrity!=null&&integrity.getAlgorithm()!=null){
                    String integResult = testIntegrity(integrity.getAlgorithm(),protocol);
                    if(integResult.equals("inner error")) {
                        status = false;
                    }
                    Thread.sleep(150);
                    //String integResult = "vertify ok ,using method: MD5 ,time:19 ms";
                    resultMap.put("integrityResult",integResult);
                }
                if(encrypt!=null&&encrypt.getAlgorithm()!=null){

                    String encryptResult = testEncrypt(encrypt.getAlgorithm(),protocol);
                    if(encryptResult.equals("inner error")){
                        status = false;
                    }

                    Thread.sleep(150);

                    //String encryptResult = "encrypt ok ,using method: AES ,time:78 ms\u0000\u0000\u0000\u0000";
                    resultMap.put("encryptResult",encryptResult);
                }
                Resend resend = config.getResend();
                if(resend!=null&&resend.getQueue()!=null){
                    String resendResult = testResend(resend.getQueue(),resend.getTime(),resend.getCount(),protocol);
                    if(resendResult.equals("inner error")){
                        status = false;
                    }
                    Thread.sleep(150);
                    //String resendResult = "ARQ ok  limited times:5 ,result: 1 message has been retransferred ,time:1722 ms";
                    resultMap.put("resendResult",resendResult);
                }

                if(status!=false){
                    String result = dealTestReportSave(designId,myUsername,protocol,resultMap,attackList);
                    String testReportId = result;

                    if(testReportId!=null){
                        resultMap.put("testReportId",testReportId);

                        JSONObject jsonObject = JSONObject.fromObject(resultMap);
                        LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                        return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);
                    }else {
                        JSONObject jsonObject = JSONObject.fromObject(resultMap);
                        LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.SUCCESS);
                        return JsonUtil.successJson(CommonValue.JSON_TEST_FINISH,jsonObject,null);
                    }

                }else {
                    LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
                    return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
                }
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.TEST_TYPE,CommonValue.TEST_CONFIG_LOGINFO+",协议设计id:"+(designId.substring(6,8)+designId.substring(18)).toUpperCase(),CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }


    }

    /**
     * 切换模式
     */
    public String changeModel(String protocolName){
        Map<String,String> resultMap = new HashMap<>();
        String protocol = CommonValue.protocolMap.get(protocolName);
        if(protocol==null){
            protocol = "";
        }
        if(protocol!=null&&!protocol.isEmpty()){
            SendData sendData = new SendData();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("protocol",protocol);
            sendData.setOperation("channel");
            sendData.setParams(jsonObject);
            String json = JSONObject.fromObject(sendData).toString();
            String result = HttpUtil.postRequest(CommonValue.IP,json);
            resultMap.put("modelResult",result);
            JSONObject jsonObj = JSONObject.fromObject(resultMap);
            System.out.println(jsonObj.toString());
            if (result.contains("done")){
                return JsonUtil.successJson(CommonValue.JSON_MODEL_SUCCESS,jsonObj,null);
            }else {
                return JsonUtil.failedJson(CommonValue.JSON_MODEL_FAILED);
                //return JsonUtil.successJson(CommonValue.JSON_MODEL_SUCCESS,jsonObj,null);
            }
        }else {
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 认证协商
     * @param method
     * @return
     */
    public String authNegotiation(String method,String protocol){
        SendData sendData = new SendData();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","authentication");
        jsonObject.put("method",method);
        jsonObject.put("protocol",protocol);
        jsonObject.put("attack","man-in-the-middle");
        sendData.setOperation("negotiation");
        sendData.setParams(jsonObject);
        String json = JSONObject.fromObject(sendData).toString();
        String result = HttpUtil.postRequest(CommonValue.IP,json);
        //String result = "one rtt authentication ok  ,key: 1nnKOx7E9Gs4wSu8CjHSH/XZFtdS2VDQD1B1U2ClSQk= ,time:8.925 ms ,clientRandom:IgY1eu9PowM6ZhcdxXtHS6tHSAqM9VuT,severRandom:TUlJWDFHNEM0b2h3bzRHX1ZFaEs3X01mdF9yWXJucWQ=,mac:8583201126,SS:null,start time:2019/08/09 12:02:12:492,end time:2019/08/09 12:02:12:501,攻击类型选择:中间人攻击,攻击过程信息:接收传输随机数种子:IgY1eu9PowM6ZhcdxXtHS6tHSAqM9VuT ,构造随机数种子:VFVsSldERkhORU0wYjJoM2J6UkhYMVpGYUVzM1gwMW1kRjl5V1hKdWNXUT0K,随机数验证不通过 成功识别中间人攻击";
        //String result = "zero rtt authentication ok,key: anlPCxIg8quSqQFhkHLABiWZ58iFPwEnTtgsJ1p8Kb4=  ,time:6.141 ms ,clientRandom:JRRZCTpnwILlwyCKJvPyfuFcx59Rh3k1,severRandom:M2tvV0JMYjgxUlFveGJJdjI3NEFsaXhibzlIMWZ1ZWo= ,mac:9892953763,SS:gv7dPIYqyMuT6NRRZ/k/76VvtGdlFVw0HTSSWFFRJ90= ,start time:2019/08/07 17:44:22:498,end time:2019/08/07 17:44:22:504,攻击类型选择:中间人攻击,攻击过程信息:接收传输随机数种子:JRRZCTpnwILlwyCKJvPyfuFcx59Rh3k1 ,构造随机数种子:TTJ0dlYwSk1Zamd4VWxGdmVHSkpkakkzTkVGc2FYaGliemxJTVdaMVpXbz0K ,随机数验证不通过 成功识别中间人攻击";
        //String result = "zero rtt authentication ok,key: uL8aaRqY3oRzMMX3N5eO5S2cMnMzoCWhPut6NvFd29o=  ,time:3.527 ms ,clientRandom:pChREA4a3Srs91_JOtCcJExAb4m1TN6h,severRandom:zmkKPuOz9x6GF2iopdsV8IzZgE1UIwog,mac:5722523097, SS:y606lPM+Ygp0K/cskJFN8cNs7of0KGDVm1PUUEbyxaY= ,攻击类型选择:中间人攻击,攻击过程信息:接收传输随机数种子:pChREA4a3Srs91_JOtCcJExAb4m1TN6h ,构造随机数种子:pChREA4a3Srs91_JOtCcJExAb4m1TN6h,随机数验证不通过 成功识别中间人攻击\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";

        return result;
    }

    /**
     * 加密协商
     * @param method
     * @param model
     * @param data
     * @return
     */
    public String encryptNegotiation(String method,String model,String data,String protocol){

        SendData sendData = new SendData();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type","encrypt");
        jsonObject.put("method",method);
        jsonObject.put("model",model);
        jsonObject.put("data",data);
        jsonObject.put("protocol",protocol);
        sendData.setOperation("negotiation");
        sendData.setParams(jsonObject);
        String json = JSONObject.fromObject(sendData).toString();
        String result = HttpUtil.postRequest(CommonValue.IP,json);
        //String result = "encryptNegotiate ok, host has received clipers,time:2.944 ms,start time:2019/08/07 19:31:06:997,end time:2019/08/07 19:31:06:000";
        //String result = "encryptNegotiate ok, host has received clipers ,time:1.094 ms\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";

        return result;
    }

    /**
     * 测试异常
     * @return
     */
    public String testException(String protocol){
        SendData sendData = new SendData();
        sendData.setOperation("def");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("protocol",protocol);
        jsonObject.put("attack","packet-theft");
        sendData.setParams(jsonObject);
        String json = JSONObject.fromObject(sendData).toString();
        String result = HttpUtil.postRequest(CommonValue.IP,json);
        //String result = "scaning ok  ,using scaning tools   ,time:0.048 ms,head length:40,head:RQAAQ2WNQAB/BhG7wKgBDsCoAg7CUE4gXtiELDZJv4pQGAD87QQAAA==,total_length:70,actual length:73,result: error packet found,start time:2019/08/07 17:44:29:081,end time:2019/08/07 17:44:29:081,攻击类型选择:数据包篡改, 攻击过程信息:篡改数据包长度为:73,检测到长度不匹配， 安全协议成功识别数据包篡改";
        //String result = "scaning ok  ,using scaning tools   ,time:3 ms,head length:40,head:RQAAQ74WQAA/BvkxwKgBDsCoAg7u/04gVlHsIbJXwhpQGAP/VDwAAA==,total_length:70,actual length:73,result: error packet found,攻击类型选择:数据包篡改, 攻击过程信息:篡改数据包长度为:73,检测到长度不匹配， 安全协议成功识别数据包篡改\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";

        return result;
    }

    /**
     * 测试完整性
     * @param method
     * @return
     */
    public String testIntegrity(String method,String protocol){
        SendData sendData = new SendData();
        sendData.setOperation("hash");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("method",method);
        jsonObject.put("protocol",protocol);
        jsonObject.put("attack","packet-theft");
        sendData.setParams(jsonObject);
        String json = JSONObject.fromObject(sendData).toString();
        String result = HttpUtil.postRequest(CommonValue.IP,json);
        //String result = "vertify ok ,using method: MD5 ,time:0.037 ms,hash value:8790 ,data_area:RQAAQ2WPQAB/BhG5wKgBDsCoAg7CUE4gXtiEVjZJv+VQGA,verify value:2780,start time:2019/08/07 17:44:31:819,end time:2019/08/07 17:44:31:819,攻击类型选择:数据包篡改,攻击过程信息:篡改前校验值:8790 ,篡改后校验值:2780,校验不通过,安全协议成功识别数据包篡改";
        //String result = "vertify ok ,using method: MD5 ,time:0.026 ms, hash value:1002, data_area:RQAAQ744QAA/BvkPwKgBDsCoAg7u/04gVlHt3bJXyqNQGA,verify value:6210,攻击类型选择:数据包篡改,攻击过程信息:篡改前校验值:1002 ,篡改后校验值:6210,校验不通过,安全协议成功识别数据包篡改";

        return result;
    }

    /**
     * 测试重传
     * @param round
     * @param RTO
     * @param limit
     * @return
     */
    public String testResend(String round,String RTO,String limit,String protocol){
        SendData sendData = new SendData();
        sendData.setOperation("arq");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("round",round);
        jsonObject.put("RTO",RTO);
        jsonObject.put("limit",limit);
        jsonObject.put("protocol",protocol);
        jsonObject.put("attack","packet-replay");
        sendData.setParams(jsonObject);
        String json = JSONObject.fromObject(sendData).toString();
        String result = HttpUtil.postRequest(CommonValue.IP,json);
        //String result = "ARQ ok ,using arq methods,time:9.117 ms,result:all message has been received,arq times:0,success arq times:5, arq_order:12345, rto:1.000ms,start time:2019/08/07 19:31:20:846,end time:2019/08/07 19:31:20:899,攻击类型选择: 重放攻击, 攻击过程信息:重放标号为3的数据包，重传队列序号重复，安全协议成功识别重放攻击";
        //String result = "ARQ ok ,but sssss, time:3.064 ms, result:2 message has been retransferred,arq times:2,success arq times:2, arq_order:12345, rto:0.010ms,攻击类型选择: 重放攻击, 攻击过程信息:重放标号为3的数据包，重传队列序号重复，安全协议成功识别重放攻击";
        //String result = "ARQ ok ,using arq methods, time:3.064 ms, result:2 message has been retransferred,arq times:2,success arq times:2, arq_order:12345, rto:0.010ms,攻击类型选择: 重放攻击, 攻击过程信息:重放标号为3的数据包，重传队列序号重复，安全协议成功识别重放攻击";

        return result;
    }

    /**
     * 加密测试
     * @param method
     * @return
     */
    public String testEncrypt(String method,String protocol){
        SendData sendData = new SendData();
        sendData.setOperation("encrypt");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("method",method);
        jsonObject.put("protocol",protocol);
        jsonObject.put("attack","packet-listening");
        sendData.setParams(jsonObject);
        String json = JSONObject.fromObject(sendData).toString();
        String result = HttpUtil.postRequest(CommonValue.IP,json);
        //String result = "encrypt ok ,using method: 3DES ,time:0.055 ms,data before: 0x51 41 42 2f 42 68 47 2b 77 4b 67 42 44 73 43 6f 41 67 37 43 55 45 34 67 ,data after: 4gXtiEAjZJvy9QGAD8q5oAADAwMDAzNi ,using key:a2lqbmF3aWt3aWd1,start time:2019/08/07 17:44:25:865,end time:2019/08/07 17:44:25:865 ,攻击类型选择:数据包窃听，攻击过程信息:接收密文: 4gXtiEAjZJvy9QGAD8q5oAADAwMDAzNi , 随机生成密钥:O4MWW2_grYNRJIA7 ,解密后数据:NGdYdGlFQWpaSnZ5OVFHQUQ4cTVvQUFEQXdNREF6Tmk=,攻击者无法识别密文，安全协议能够抵御数据包窃听";
        //String result = "encrypt ok ,using method: AES ,time:0.06 ms, data before: RQAAQ75yQAA/BvjVwKgBDsCo,data after: RQAAQ75yQAA/BvjVwKgBDsCoAg7u/04g ,using key:a2lqbmF3aWt3aWd1  ,攻击类型选择:数据包窃听，攻击过程信息:接收密文: RQAAQ75yQAA/BvjVwKgBDsCoAg7u/04g , 随机生成密钥:r41VtZ3txWOoME1w ,解密后数据:r41VtZ3txWOoME1wu6w5M6tOeFS3lIUO,攻击者无法识别密文，安全协议能够抵御数据包窃听\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";

        return result;
    }

    /**
     * 预处理信息
     * @param protocol
     * @param ept
     * @param ic
     * @param ad
     * @param ealgor
     * @param emode
     * @param ialgor
     * @param aalgor
     */
    public void preMessage(String protocol,String ept,String ic,String ad,String ealgor,String emode,String ialgor,String aalgor,String Auto){
        SendData sendData = new SendData();
        sendData.setOperation("head");
        JSONObject jsonObject = new JSONObject();
        protocol = CommonValue.protocolMap.get(protocol);
        if(protocol==null){
            protocol = "";
        }
        jsonObject.put("protocol",protocol);
        jsonObject.put("EPT",ept);
        jsonObject.put("IC",ic);
        jsonObject.put("AD",ad);
        jsonObject.put("EAlgor",ealgor);
        jsonObject.put("EMode",emode);
        jsonObject.put("IAlgor",ialgor);
        jsonObject.put("AAlgor",aalgor);
        jsonObject.put("auto",Auto);
        sendData.setParams(jsonObject);
        String json = JSONObject.fromObject(sendData).toString();
        HttpUtil.postRequest(CommonValue.IP,json);
    }

}
